/**
 * 主应用程序
 */
class TaskTrackApp {
    constructor() {
        this.currentTab = 'dashboard';
        this.currentUser = null;
        this.demands = [];
        this.workflows = {};
        this.demandTypes = {};
        this.urgencyLevels = [];
        this.users = [];
        this.filters = {
            type: '',
            urgency: ''
        };
        
        // 组件实例
        this.workflowPreview = null;
    }
    
    /**
     * 初始化应用
     */
    async init() {
        try {
            // 检查登录状态
            const savedUser = localStorage.getItem('currentUser');
            if (savedUser) {
                this.currentUser = JSON.parse(savedUser);
                this.showMainApp();
                await this.initMainApp();
            } else {
                this.showLoginPage();
            }
            
            this.setupLoginEvents();
        } catch (error) {
            console.error('应用初始化失败:', error);
            this.showMessage('应用初始化失败: ' + error.message, 'error');
        }
    }
    
    /**
     * 显示登录页面
     */
    showLoginPage() {
        document.getElementById('login-page').classList.add('active');
        document.getElementById('main-app').classList.remove('active');
    }
    
    /**
     * 显示主应用
     */
    showMainApp() {
        document.getElementById('login-page').classList.remove('active');
        document.getElementById('main-app').classList.add('active');
        
        if (this.currentUser) {
            document.getElementById('current-user').textContent = this.currentUser.name;
        }
    }
    
    /**
     * 设置登录事件
     */
    setupLoginEvents() {
        const loginForm = document.getElementById('login-form');
        if (loginForm) {
            loginForm.addEventListener('submit', (e) => {
                e.preventDefault();
                this.handleLogin();
            });
        }
        
        const logoutBtn = document.getElementById('logout-btn');
        if (logoutBtn) {
            logoutBtn.addEventListener('click', () => {
                this.handleLogout();
            });
        }
    }
    
    /**
     * 处理登录
     */
    async handleLogin() {
        try {
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;
            
            if (!username || !password) {
                this.showMessage('请输入用户名和密码', 'warning');
                return;
            }
            
            // 初始化数据管理器
            await window.dataManager.initialize();
            
            // 加载用户数据
            let users;
            try {
                users = await window.dataManager.getUsers();
            } catch (error) {
                console.warn('获取用户数据失败，使用默认用户:', error);
                // 如果获取用户数据失败，使用默认管理员账号
                users = window.giteeAPI.getDefaultUsers();
            }
            
            // 验证用户
            const user = users.find(u => u.username === username && u.password === password && (u.isActive !== false));
            
            if (user) {
                this.currentUser = user;
                localStorage.setItem('currentUser', JSON.stringify(user));
                
                // 尝试更新最后登录时间
                try {
                    user.lastLogin = new Date().toISOString();
                    await window.dataManager.updateUser(user);
                } catch (error) {
                    console.warn('更新用户登录时间失败:', error);
                }
                
                this.showMainApp();
                await this.initMainApp();
                this.showMessage('登录成功', 'success');
            } else {
                this.showMessage('用户名或密码错误', 'error');
            }
        } catch (error) {
            console.error('登录失败:', error);
            this.showMessage('登录失败: ' + error.message, 'error');
        }
    }
    
    /**
     * 处理退出登录
     */
    handleLogout() {
        this.currentUser = null;
        localStorage.removeItem('currentUser');
        this.showLoginPage();
        
        // 清空表单
        document.getElementById('login-form').reset();
        this.showMessage('已退出登录', 'info');
    }
    
    /**
     * 初始化主应用
     */
    async initMainApp() {
        try {
            this.showLoading(true);
            
            // 初始化数据管理器
            await window.dataManager.initialize();
            
            // 初始化流程引擎
            await window.workflowEngine.initialize();
            
            // 加载数据
            await this.loadData();
            
            // 初始化UI
            this.initUI();
            
            // 设置事件监听器
            this.setupEventListeners();
            
            // 渲染初始界面
            this.renderDashboard();
            
        } catch (error) {
            console.error('主应用初始化失败:', error);
            this.showMessage('主应用初始化失败: ' + error.message, 'error');
        } finally {
            this.showLoading(false);
        }
    }
    
    /**
     * 加载数据
     */
    async loadData() {
        try {
            this.demands = await window.dataManager.getDemands();
            this.workflows = await window.dataManager.getWorkflows();
            this.demandTypes = await window.dataManager.getDemandTypes();
            this.urgencyLevels = await window.dataManager.getUrgencyLevels();
            this.users = await window.dataManager.getUsers();
        } catch (error) {
            console.error('加载数据失败:', error);
            throw error;
        }
    }
    
    /**
     * 初始化UI
     */
    initUI() {
        // 填充下拉选项
        this.populateSelects();
        
        // 更新连接状态
        this.updateConnectionStatus();
        
        // 根据用户权限显示/隐藏功能
        this.updateUIByPermissions();
    }
    
    /**
     * 根据用户权限更新UI
     */
    updateUIByPermissions() {
        const userTab = document.querySelector('[data-tab="users"]');
        if (userTab) {
            userTab.style.display = this.currentUser.permissions.manageUsers ? 'block' : 'none';
        }
        
        const workflowTab = document.querySelector('[data-tab="workflows"]');
        if (workflowTab) {
            workflowTab.style.display = this.currentUser.permissions.configureWorkflow ? 'block' : 'none';
        }
        
        const settingsTab = document.querySelector('[data-tab="settings"]');
        if (settingsTab) {
            settingsTab.style.display = this.currentUser.permissions.systemSettings ? 'block' : 'none';
        }
    }
    
    /**
     * 填充下拉选项
     */
    populateSelects() {
        // 需求类型选项
        const typeSelects = ['filter-type', 'quick-type'];
        typeSelects.forEach(selectId => {
            const select = document.getElementById(selectId);
            if (select) {
                const isFilter = selectId.includes('filter');
                select.innerHTML = isFilter ? '<option value="">所有类型</option>' : '<option value="">请选择类型</option>';
                
                Object.entries(this.demandTypes).forEach(([key, type]) => {
                    if (type.enabled) {
                        select.innerHTML += `
                            <option value="${key}">${type.icon} ${type.name}</option>
                        `;
                    }
                });
            }
        });
        
        // 紧急度选项
        const urgencySelect = document.getElementById('filter-urgency');
        if (urgencySelect) {
            urgencySelect.innerHTML = '<option value="">所有紧急度</option>';
            this.urgencyLevels.forEach(level => {
                urgencySelect.innerHTML += `
                    <option value="${level.id}">${level.name}</option>
                `;
            });
        }
        
        // 流程配置中的需求类型选项
        const workflowTypeSelect = document.getElementById('workflow-type');
        if (workflowTypeSelect) {
            workflowTypeSelect.innerHTML = '<option value="">请选择需求类型</option>';
            Object.entries(this.demandTypes).forEach(([key, type]) => {
                if (type.enabled) {
                    workflowTypeSelect.innerHTML += `
                        <option value="${key}">${type.icon} ${type.name}</option>
                    `;
                }
            });
        }
    }
    
    /**
     * 设置事件监听器
     */
    setupEventListeners() {
        // 标签页切换
        document.querySelectorAll('.nav-tab').forEach(tab => {
            tab.addEventListener('click', (e) => {
                this.switchTab(e.target.dataset.tab);
            });
        });
        
        // 同步按钮
        const syncBtn = document.getElementById('sync-btn');
        if (syncBtn) {
            syncBtn.addEventListener('click', () => {
                this.syncData();
            });
        }
        
        // 快速添加任务按钮
        document.querySelectorAll('.add-task-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const status = e.target.dataset.status;
                this.showQuickAddModal(status);
            });
        });
        
        // 快速添加表单
        const quickAddForm = document.getElementById('quick-add-form');
        if (quickAddForm) {
            quickAddForm.addEventListener('submit', (e) => {
                e.preventDefault();
                this.createQuickTask();
            });
        }
        
        // 过滤器变化
        ['filter-type', 'filter-urgency'].forEach(id => {
            const element = document.getElementById(id);
            if (element) {
                element.addEventListener('change', () => {
                    this.updateFilters();
                    this.renderDashboard();
                });
            }
        });
        
        // 用户管理事件
        this.setupUserManagementEvents();
        
        // 流程配置事件
        this.setupWorkflowEvents();
        
        // 设置页面事件
        this.setupSettingsEvents();
        
        // 模态框关闭
        document.querySelectorAll('.modal-close').forEach(btn => {
            btn.addEventListener('click', () => {
                this.closeModal();
            });
        });
        
        // 数据管理器事件
        window.dataManager.addEventListener('dataChanged', (data) => {
            this.onDataChanged(data);
        });
        
        window.dataManager.addEventListener('syncStatusChanged', (status) => {
            this.onSyncStatusChanged(status);
        });
    }
    
    /**
     * 设置用户管理事件
     */
    setupUserManagementEvents() {
        const addUserBtn = document.getElementById('add-user-btn');
        if (addUserBtn) {
            addUserBtn.addEventListener('click', () => {
                this.showUserModal();
            });
        }
        
        const userForm = document.getElementById('user-form');
        if (userForm) {
            userForm.addEventListener('submit', (e) => {
                e.preventDefault();
                this.saveUser();
            });
        }
    }
    
    /**
     * 设置流程配置事件
     */
    setupWorkflowEvents() {
        const addWorkflowBtn = document.getElementById('add-workflow-btn');
        if (addWorkflowBtn) {
            addWorkflowBtn.addEventListener('click', () => {
                this.showWorkflowModal();
            });
        }
        
        const workflowForm = document.getElementById('workflow-form');
        if (workflowForm) {
            workflowForm.addEventListener('submit', (e) => {
                e.preventDefault();
                this.saveWorkflow();
            });
        }
        
        const addNodeBtn = document.getElementById('add-node-btn');
        if (addNodeBtn) {
            addNodeBtn.addEventListener('click', () => {
                this.addWorkflowNode();
            });
        }
    }
    
    /**
     * 设置设置页面事件
     */
    setupSettingsEvents() {
        // Gitee配置测试
        const testBtn = document.getElementById('test-gitee-connection');
        if (testBtn) {
            testBtn.addEventListener('click', () => {
                this.testGiteeConnection();
            });
        }
        
        // 数据管理
        const exportBtn = document.getElementById('export-data');
        if (exportBtn) {
            exportBtn.addEventListener('click', () => {
                this.exportData();
            });
        }
        
        const importBtn = document.getElementById('import-data');
        const importFile = document.getElementById('import-file');
        if (importBtn && importFile) {
            importBtn.addEventListener('click', () => {
                importFile.click();
            });
            
            importFile.addEventListener('change', (e) => {
                if (e.target.files.length > 0) {
                    this.importData(e.target.files[0]);
                }
            });
        }
        
        const clearBtn = document.getElementById('clear-local-data');
        if (clearBtn) {
            clearBtn.addEventListener('click', () => {
                this.clearLocalData();
            });
        }
    }
    
    /**
     * 切换标签页
     */
    switchTab(tabName) {
        // 更新导航状态
        document.querySelectorAll('.nav-tab').forEach(tab => {
            tab.classList.remove('active');
        });
        document.querySelector(`[data-tab="${tabName}"]`).classList.add('active');
        
        // 显示对应内容
        document.querySelectorAll('.tab-content').forEach(content => {
            content.classList.remove('active');
        });
        document.getElementById(`${tabName}-tab`).classList.add('active');
        
        this.currentTab = tabName;
        
        // 根据标签页加载对应内容
        switch (tabName) {
            case 'dashboard':
                this.renderDashboard();
                break;
            case 'workflows':
                this.renderWorkflows();
                break;
            case 'users':
                this.renderUsers();
                break;
            case 'settings':
                this.renderSettings();
                break;
        }
    }
    
    /**
     * 显示快速添加模态框
     */
    showQuickAddModal(status) {
        const modal = document.getElementById('quick-add-modal');
        const statusInput = document.getElementById('quick-status');
        const title = document.getElementById('quick-add-title');
        
        statusInput.value = status;
        
        const statusNames = {
            'pending': '待处理',
            'in_progress': '进行中',
            'completed': '已完成',
            'rejected': '已拒绝'
        };
        
        title.textContent = `添加任务到 ${statusNames[status]}`;
        modal.classList.add('active');
    }
    
    /**
     * 创建快速任务
     */
    async createQuickTask() {
        try {
            const formData = this.getFormData('quick-add-form');
            
            if (!formData.title || !formData.demandType) {
                this.showMessage('请填写必填字段', 'warning');
                return;
            }
            
            // 创建需求对象
            const demand = {
                title: formData.title,
                description: formData.description || '',
                demandType: formData.demandType,
                status: formData.status,
                urgencyLevel: 2, // 默认正常优先级
                deadline: formData.deadline || null,
                estimatedValue: 0,
                tags: [],
                createdBy: this.currentUser.id,
                createdAt: new Date().toISOString(),
                updatedAt: new Date().toISOString()
            };
            
            // 创建流程
            demand.workflow = window.workflowEngine.createWorkflow(demand.demandType, demand.id);
            
            const result = await window.dataManager.addDemand(demand);
            
            if (result.success) {
                this.showMessage('任务创建成功', 'success');
                this.resetForm('quick-add-form');
                this.closeModal();
                
                // 刷新数据并更新看板
                await this.loadData();
                this.renderDashboard();
            } else {
                this.showMessage('创建失败: ' + result.message, 'error');
            }
        } catch (error) {
            console.error('创建任务失败:', error);
            this.showMessage('创建失败: ' + error.message, 'error');
        }
    }
    
    /**
     * 更新过滤器
     */
    updateFilters() {
        this.filters.type = document.getElementById('filter-type')?.value || '';
        this.filters.urgency = document.getElementById('filter-urgency')?.value || '';
    }
    
    /**
     * 渲染需求看板
     */
    renderDashboard() {
        // 过滤需求
        let filteredDemands = this.demands.filter(demand => {
            if (this.filters.type && demand.demandType !== this.filters.type) return false;
            if (this.filters.urgency && demand.urgencyLevel != this.filters.urgency) return false;
            return true;
        });
        
        // 按状态分组
        const statusGroups = {
            'pending': [],
            'in_progress': [],
            'completed': [],
            'rejected': []
        };
        
        filteredDemands.forEach(demand => {
            if (statusGroups[demand.status]) {
                statusGroups[demand.status].push(demand);
            }
        });
        
        // 渲染每个状态列
        Object.entries(statusGroups).forEach(([status, demands]) => {
            const container = document.getElementById(`tasks-${status}`);
            const countElement = document.getElementById(`count-${status}`);
            
            if (container) {
                container.innerHTML = demands.length === 0 ? 
                    '<div class="empty-state">暂无任务</div>' :
                    demands.map(demand => this.renderDemandCard(demand)).join('');
            }
            
            if (countElement) {
                countElement.textContent = demands.length;
            }
        });
    }
    
    /**
     * 渲染需求卡片
     */
    renderDemandCard(demand) {
        const demandType = this.demandTypes[demand.demandType];
        const urgency = this.calculateDemandUrgency(demand);
        
        return `
            <div class="demand-card" data-demand-id="${demand.id}" onclick="app.viewDemandDetails('${demand.id}')">
                <div class="demand-card-header">
                    <div class="demand-type">
                        ${demandType?.icon || '📋'} ${demandType?.name || '未知类型'}
                    </div>
                    <div class="demand-urgency ${urgency.level}">
                        ${urgency.label}
                    </div>
                </div>
                <div class="demand-card-title">${this.escapeHtml(demand.title)}</div>
                ${demand.description ? `
                    <div class="demand-card-description">
                        ${this.escapeHtml(demand.description.substring(0, 100))}${demand.description.length > 100 ? '...' : ''}
                    </div>
                ` : ''}
                <div class="demand-card-footer">
                    <div class="demand-meta">
                        ${demand.deadline ? `
                            <span class="demand-deadline">
                                📅 ${new Date(demand.deadline).toLocaleDateString()}
                            </span>
                        ` : ''}
                        <span class="demand-creator">
                            👤 ${this.getUserName(demand.createdBy)}
                        </span>
                    </div>
                    ${demand.tags && demand.tags.length > 0 ? `
                        <div class="demand-tags">
                            ${demand.tags.slice(0, 2).map(tag => `<span class="demand-tag">${tag}</span>`).join('')}
                            ${demand.tags.length > 2 ? `<span class="demand-tag">+${demand.tags.length - 2}</span>` : ''}
                        </div>
                    ` : ''}
                </div>
            </div>
        `;
    }
    
    /**
     * 计算需求紧急度
     */
    calculateDemandUrgency(demand) {
        if (!demand.deadline) {
            return { level: 'low', color: '#6c757d', label: '低优先级' };
        }
        
        const deadline = new Date(demand.deadline);
        const now = new Date();
        const diffTime = deadline - now;
        const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
        
        for (const level of this.urgencyLevels.sort((a, b) => a.days - b.days)) {
            if (diffDays <= level.days) {
                return {
                    level: level.name.toLowerCase(),
                    color: level.color,
                    label: level.name
                };
            }
        }
        
        return { level: 'low', color: '#6c757d', label: '低优先级' };
    }
    
    /**
     * 获取用户名称
     */
    getUserName(userId) {
        const user = this.users.find(u => u.id === userId);
        return user ? user.name : '未知用户';
    }
    
    /**
     * 渲染用户管理页面
     */
    renderUsers() {
        const container = document.getElementById('users-list');
        if (!container) return;
        
        container.innerHTML = this.users.map(user => `
            <div class="user-item">
                <div class="user-item-header">
                    <div class="user-item-name">${user.name} (${user.username})</div>
                    <div class="user-item-actions">
                        <button class="btn btn-sm btn-secondary" onclick="app.editUser('${user.id}')">编辑</button>
                        ${user.id !== 'admin' ? `
                            <button class="btn btn-sm btn-danger" onclick="app.deleteUser('${user.id}')">删除</button>
                        ` : ''}
                    </div>
                </div>
                <div class="user-item-info">
                    <div>邮箱: ${user.email || '未设置'}</div>
                    <div>角色: ${user.roles.join(', ')}</div>
                    <div>状态: ${user.isActive ? '✅ 活跃' : '❌ 禁用'}</div>
                    <div>最后登录: ${user.lastLogin ? new Date(user.lastLogin).toLocaleString() : '从未登录'}</div>
                </div>
            </div>
        `).join('');
    }
    
    /**
     * 显示用户模态框
     */
    showUserModal(userId = null) {
        const modal = document.getElementById('user-modal');
        const title = document.getElementById('user-modal-title');
        const form = document.getElementById('user-form');
        
        if (userId) {
            const user = this.users.find(u => u.id === userId);
            if (user) {
                title.textContent = '编辑用户';
                document.getElementById('user-id').value = user.id;
                document.getElementById('user-username').value = user.username;
                document.getElementById('user-password').value = user.password;
                document.getElementById('user-name').value = user.name;
                document.getElementById('user-email').value = user.email || '';
                
                // 设置角色选择
                const rolesSelect = document.getElementById('user-roles');
                Array.from(rolesSelect.options).forEach(option => {
                    option.selected = user.roles.includes(option.value);
                });
            }
        } else {
            title.textContent = '添加用户';
            form.reset();
            document.getElementById('user-id').value = '';
        }
        
        modal.classList.add('active');
    }
    
    /**
     * 保存用户
     */
    async saveUser() {
        try {
            const formData = this.getFormData('user-form');
            
            if (!formData.username || !formData.password || !formData.name) {
                this.showMessage('请填写必填字段', 'warning');
                return;
            }
            
            const userId = formData.id || `user_${Date.now()}`;
            const isEdit = !!formData.id;
            
            // 检查用户名是否重复
            const existingUser = this.users.find(u => u.username === formData.username && u.id !== userId);
            if (existingUser) {
                this.showMessage('用户名已存在', 'warning');
                return;
            }
            
            const rolesSelect = document.getElementById('user-roles');
            const selectedRoles = Array.from(rolesSelect.selectedOptions).map(option => option.value);
            
            const user = {
                id: userId,
                username: formData.username,
                password: formData.password,
                name: formData.name,
                email: formData.email || '',
                roles: selectedRoles,
                permissions: this.generateUserPermissions(selectedRoles),
                createdAt: isEdit ? this.users.find(u => u.id === userId)?.createdAt : new Date().toISOString(),
                lastLogin: isEdit ? this.users.find(u => u.id === userId)?.lastLogin : null,
                isActive: true
            };
            
            const result = isEdit ? 
                await window.dataManager.updateUser(user) :
                await window.dataManager.addUser(user);
            
            if (result.success) {
                this.showMessage(isEdit ? '用户更新成功' : '用户创建成功', 'success');
                this.closeModal();
                await this.loadData();
                this.renderUsers();
            } else {
                this.showMessage('保存失败: ' + result.message, 'error');
            }
        } catch (error) {
            console.error('保存用户失败:', error);
            this.showMessage('保存失败: ' + error.message, 'error');
        }
    }
    
    /**
     * 根据角色生成用户权限
     */
    generateUserPermissions(roles) {
        const permissions = {
            createDemand: false,
            editDemand: false,
            deleteDemand: false,
            viewAllDemands: false,
            configureWorkflow: false,
            markComplete: false,
            addSignNode: false,
            manageUsers: false,
            systemSettings: false
        };
        
        roles.forEach(role => {
            switch (role) {
                case '管理员':
                    Object.keys(permissions).forEach(key => {
                        permissions[key] = true;
                    });
                    break;
                case '产品评估':
                    permissions.createDemand = true;
                    permissions.editDemand = true;
                    permissions.viewAllDemands = true;
                    permissions.markComplete = true;
                    break;
                case '计划制定':
                case '执行跟进':
                    permissions.editDemand = true;
                    permissions.viewAllDemands = true;
                    permissions.markComplete = true;
                    break;
            }
        });
        
        return permissions;
    }
    
    /**
     * 编辑用户
     */
    editUser(userId) {
        this.showUserModal(userId);
    }
    
    /**
     * 删除用户
     */
    async deleteUser(userId) {
        if (userId === 'admin') {
            this.showMessage('不能删除管理员账户', 'warning');
            return;
        }
        
        if (confirm('确定要删除这个用户吗？')) {
            try {
                const result = await window.dataManager.deleteUser(userId);
                if (result.success) {
                    this.showMessage('用户删除成功', 'success');
                    await this.loadData();
                    this.renderUsers();
                } else {
                    this.showMessage('删除失败: ' + result.message, 'error');
                }
            } catch (error) {
                console.error('删除用户失败:', error);
                this.showMessage('删除失败: ' + error.message, 'error');
            }
        }
    }
    
    /**
     * 渲染流程配置页面
     */
    renderWorkflows() {
        const container = document.getElementById('workflows-list');
        if (!container) return;
        
        container.innerHTML = Object.entries(this.workflows).map(([key, workflow]) => `
            <div class="workflow-item">
                <div class="workflow-item-header">
                    <div class="workflow-item-name">${workflow.name}</div>
                    <div class="workflow-item-actions">
                        <button class="btn btn-sm btn-secondary" onclick="app.editWorkflow('${key}')">编辑</button>
                        <button class="btn btn-sm btn-danger" onclick="app.deleteWorkflow('${key}')">删除</button>
                    </div>
                </div>
                <div class="workflow-item-info">
                    <div>关联类型: ${this.demandTypes[workflow.demandType]?.name || '未知'}</div>
                    <div>节点数量: ${workflow.nodes.length}</div>
                    <div>描述: ${workflow.description || '无描述'}</div>
                </div>
                <div class="workflow-nodes-preview">
                    ${workflow.nodes.map(node => `
                        <span class="workflow-node-preview">${node.name}</span>
                    `).join(' → ')}
                </div>
            </div>
        `).join('');
    }
    
    /**
     * 显示流程配置模态框
     */
    showWorkflowModal(workflowId = null) {
        const modal = document.getElementById('workflow-modal');
        const title = document.getElementById('workflow-modal-title');
        const form = document.getElementById('workflow-form');
        
        if (workflowId) {
            const workflow = this.workflows[workflowId];
            if (workflow) {
                title.textContent = '编辑流程';
                document.getElementById('workflow-id').value = workflowId;
                document.getElementById('workflow-name').value = workflow.name;
                document.getElementById('workflow-type').value = workflow.demandType;
                document.getElementById('workflow-description').value = workflow.description || '';
                
                this.renderWorkflowNodes(workflow.nodes);
            }
        } else {
            title.textContent = '添加流程';
            form.reset();
            document.getElementById('workflow-id').value = '';
            this.renderWorkflowNodes([]);
        }
        
        modal.classList.add('active');
    }
    
    /**
     * 渲染流程节点配置
     */
    renderWorkflowNodes(nodes = []) {
        const container = document.getElementById('workflow-nodes-list');
        if (!container) return;
        
        container.innerHTML = nodes.map((node, index) => `
            <div class="workflow-node-config" data-node-index="${index}">
                <div class="node-config-header">
                    <span>节点 ${index + 1}</span>
                    <button type="button" class="btn btn-sm btn-danger" onclick="app.removeWorkflowNode(${index})">删除</button>
                </div>
                <div class="node-config-body">
                    <div class="form-row">
                        <div class="form-group">
                            <label>节点名称</label>
                            <input type="text" name="node-name-${index}" value="${node.name}" required>
                        </div>
                        <div class="form-group">
                            <label>默认负责人</label>
                            <select name="node-assignee-${index}">
                                <option value="">请选择</option>
                                ${this.users.map(user => `
                                    <option value="${user.id}" ${node.defaultAssignee === user.id ? 'selected' : ''}>
                                        ${user.name}
                                    </option>
                                `).join('')}
                            </select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label>节点描述</label>
                        <textarea name="node-description-${index}" rows="2">${node.description || ''}</textarea>
                    </div>
                </div>
            </div>
        `).join('');
    }
    
    /**
     * 添加流程节点
     */
    addWorkflowNode() {
        const container = document.getElementById('workflow-nodes-list');
        const nodeCount = container.children.length;
        
        const nodeHtml = `
            <div class="workflow-node-config" data-node-index="${nodeCount}">
                <div class="node-config-header">
                    <span>节点 ${nodeCount + 1}</span>
                    <button type="button" class="btn btn-sm btn-danger" onclick="app.removeWorkflowNode(${nodeCount})">删除</button>
                </div>
                <div class="node-config-body">
                    <div class="form-row">
                        <div class="form-group">
                            <label>节点名称</label>
                            <input type="text" name="node-name-${nodeCount}" required>
                        </div>
                        <div class="form-group">
                            <label>默认负责人</label>
                            <select name="node-assignee-${nodeCount}">
                                <option value="">请选择</option>
                                ${this.users.map(user => `
                                    <option value="${user.id}">${user.name}</option>
                                `).join('')}
                            </select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label>节点描述</label>
                        <textarea name="node-description-${nodeCount}" rows="2"></textarea>
                    </div>
                </div>
            </div>
        `;
        
        container.insertAdjacentHTML('beforeend', nodeHtml);
    }
    
    /**
     * 删除流程节点
     */
    removeWorkflowNode(index) {
        const container = document.getElementById('workflow-nodes-list');
        const nodeElement = container.querySelector(`[data-node-index="${index}"]`);
        if (nodeElement) {
            nodeElement.remove();
            
            // 重新编号
            Array.from(container.children).forEach((node, newIndex) => {
                node.dataset.nodeIndex = newIndex;
                node.querySelector('.node-config-header span').textContent = `节点 ${newIndex + 1}`;
                
                // 更新表单字段名称
                const inputs = node.querySelectorAll('input, select, textarea');
                inputs.forEach(input => {
                    const name = input.name;
                    if (name) {
                        const baseName = name.replace(/-\d+$/, '');
                        input.name = `${baseName}-${newIndex}`;
                    }
                });
                
                // 更新删除按钮
                const deleteBtn = node.querySelector('.btn-danger');
                deleteBtn.setAttribute('onclick', `app.removeWorkflowNode(${newIndex})`);
            });
        }
    }
    
    /**
     * 保存流程配置
     */
    async saveWorkflow() {
        try {
            const formData = this.getFormData('workflow-form');
            
            if (!formData.name || !formData.demandType) {
                this.showMessage('请填写必填字段', 'warning');
                return;
            }
            
            const workflowId = formData.id || formData.demandType;
            const isEdit = !!formData.id;
            
            // 收集节点数据
            const nodes = [];
            const container = document.getElementById('workflow-nodes-list');
            Array.from(container.children).forEach((nodeElement, index) => {
                const nameInput = nodeElement.querySelector(`[name="node-name-${index}"]`);
                const assigneeSelect = nodeElement.querySelector(`[name="node-assignee-${index}"]`);
                const descriptionTextarea = nodeElement.querySelector(`[name="node-description-${index}"]`);
                
                if (nameInput && nameInput.value) {
                    nodes.push({
                        id: `node_${index}`,
                        name: nameInput.value,
                        description: descriptionTextarea?.value || '',
                        defaultAssignee: assigneeSelect?.value || null,
                        order: index + 1
                    });
                }
            });
            
            if (nodes.length === 0) {
                this.showMessage('请至少添加一个流程节点', 'warning');
                return;
            }
            
            const workflow = {
                id: workflowId,
                name: formData.name,
                description: formData.description || '',
                demandType: formData.demandType,
                nodes: nodes
            };
            
            const result = await window.dataManager.saveWorkflow(workflowId, workflow);
            
            if (result.success) {
                this.showMessage(isEdit ? '流程更新成功' : '流程创建成功', 'success');
                this.closeModal();
                await this.loadData();
                this.renderWorkflows();
            } else {
                this.showMessage('保存失败: ' + result.message, 'error');
            }
        } catch (error) {
            console.error('保存流程失败:', error);
            this.showMessage('保存失败: ' + error.message, 'error');
        }
    }
    
    /**
     * 编辑流程
     */
    editWorkflow(workflowId) {
        this.showWorkflowModal(workflowId);
    }
    
    /**
     * 删除流程
     */
    async deleteWorkflow(workflowId) {
        if (confirm('确定要删除这个流程配置吗？')) {
            try {
                const result = await window.dataManager.deleteWorkflow(workflowId);
                if (result.success) {
                    this.showMessage('流程删除成功', 'success');
                    await this.loadData();
                    this.renderWorkflows();
                } else {
                    this.showMessage('删除失败: ' + result.message, 'error');
                }
            } catch (error) {
                console.error('删除流程失败:', error);
                this.showMessage('删除失败: ' + error.message, 'error');
            }
        }
    }
    
    /**
     * 同步数据
     */
    async syncData() {
        try {
            const syncBtn = document.getElementById('sync-btn');
            if (syncBtn) {
                syncBtn.classList.add('syncing');
            }
            
            const result = await window.dataManager.syncAll();
            
            if (result.success) {
                await this.loadData();
                this.renderDashboard();
                this.showMessage('数据同步成功', 'success');
            } else {
                this.showMessage('同步失败: ' + result.message, 'error');
            }
        } catch (error) {
            console.error('同步失败:', error);
            this.showMessage('同步失败: ' + error.message, 'error');
        } finally {
            const syncBtn = document.getElementById('sync-btn');
            if (syncBtn) {
                syncBtn.classList.remove('syncing');
            }
        }
    }
    
    /**
     * 测试Gitee连接
     */
    async testGiteeConnection() {
        try {
            const token = document.getElementById('gitee-token')?.value;
            const owner = document.getElementById('gitee-owner')?.value;
            const repo = document.getElementById('gitee-repo')?.value;
            
            if (!token || !owner || !repo) {
                this.showMessage('请填写完整的Gitee配置', 'warning');
                return;
            }
            
            // 设置认证信息
            window.giteeAPI.setAuth(token, owner, repo);
            
            const result = await window.giteeAPI.testConnection();
            
            if (result.success) {
                this.showMessage('连接成功', 'success');
                this.updateConnectionStatus();
            } else {
                this.showMessage('连接失败: ' + result.message, 'error');
            }
        } catch (error) {
            this.showMessage('测试失败: ' + error.message, 'error');
        }
    }
    
    /**
     * 导出数据
     */
    async exportData() {
        try {
            const result = await window.dataManager.exportData();
            if (result.success) {
                this.showMessage('数据导出成功', 'success');
            } else {
                this.showMessage('导出失败: ' + result.message, 'error');
            }
        } catch (error) {
            this.showMessage('导出失败: ' + error.message, 'error');
        }
    }
    
    /**
     * 导入数据
     */
    async importData(file) {
        try {
            const result = await window.dataManager.importData(file);
            if (result.success) {
                await this.loadData();
                this.renderDashboard();
                this.showMessage('数据导入成功', 'success');
            } else {
                this.showMessage('导入失败: ' + result.message, 'error');
            }
        } catch (error) {
            this.showMessage('导入失败: ' + error.message, 'error');
        }
    }
    
    /**
     * 清空本地数据
     */
    clearLocalData() {
        if (confirm('确定要清空所有本地数据吗？此操作不可恢复。')) {
            const result = window.dataManager.clearLocalData();
            if (result.success) {
                this.demands = [];
                this.renderDashboard();
                this.showMessage('本地数据已清空', 'success');
            }
        }
    }
    
    /**
     * 渲染设置页面
     */
    renderSettings() {
        // 填充Gitee配置
        const auth = window.giteeAPI.getAuth();
        const tokenInput = document.getElementById('gitee-token');
        const ownerInput = document.getElementById('gitee-owner');
        const repoInput = document.getElementById('gitee-repo');
        
        if (tokenInput) tokenInput.value = auth.token;
        if (ownerInput) ownerInput.value = auth.owner;
        if (repoInput) repoInput.value = auth.repo;
    }
    
    /**
     * 更新连接状态
     */
    updateConnectionStatus() {
        const statusElement = document.getElementById('connection-status');
        if (!statusElement) return;
        
        const dot = statusElement.querySelector('.status-dot');
        const text = statusElement.querySelector('.status-text');
        
        if (window.giteeAPI.isConfigured()) {
            dot.className = 'status-dot online';
            text.textContent = '已连接';
        } else {
            dot.className = 'status-dot offline';
            text.textContent = '未配置';
        }
    }
    
    /**
     * 数据变化处理
     */
    onDataChanged(data) {
        if (data.type === 'demands' || data.type === 'all') {
            this.demands = data.data || [];
            if (this.currentTab === 'dashboard') {
                this.renderDashboard();
            }
        }
    }
    
    /**
     * 同步状态变化处理
     */
    onSyncStatusChanged(status) {
        this.updateConnectionStatus();
        
        if (status.syncing) {
            this.showMessage('正在同步数据...', 'info');
        } else if (status.success) {
            this.showMessage('数据同步完成', 'success');
        } else if (status.message) {
            this.showMessage(status.message, 'error');
        }
    }
    
    /**
     * 查看需求详情
     */
    viewDemandDetails(demandId) {
        const demand = this.demands.find(d => d.id === demandId);
        if (!demand) return;
        
        const modal = document.getElementById('demand-modal');
        const modalTitle = document.getElementById('modal-title');
        const modalBody = document.getElementById('modal-body');
        
        modalTitle.textContent = demand.title;
        
        const demandType = this.demandTypes[demand.demandType];
        const urgency = this.calculateDemandUrgency(demand);
        
        modalBody.innerHTML = `
            <div class="demand-details">
                <div class="demand-info">
                    <h4>基本信息</h4>
                    <p><strong>类型:</strong> ${demandType?.icon} ${demandType?.name}</p>
                    <p><strong>状态:</strong> ${this.getStatusText(demand.status)}</p>
                    <p><strong>紧急度:</strong> <span class="urgency-indicator ${urgency.level}">${urgency.label}</span></p>
                    ${demand.deadline ? `<p><strong>截止日期:</strong> ${new Date(demand.deadline).toLocaleDateString()}</p>` : ''}
                    ${demand.estimatedValue ? `<p><strong>预估价值:</strong> ¥${demand.estimatedValue}</p>` : ''}
                    <p><strong>创建人:</strong> ${this.getUserName(demand.createdBy)}</p>
                    <p><strong>创建时间:</strong> ${new Date(demand.createdAt).toLocaleString()}</p>
                </div>
                
                ${demand.description ? `
                    <div class="demand-description">
                        <h4>需求描述</h4>
                        <p>${demand.description}</p>
                    </div>
                ` : ''}
                
                ${demand.tags && demand.tags.length > 0 ? `
                    <div class="demand-tags-section">
                        <h4>标签</h4>
                        <div class="demand-tags">
                            ${demand.tags.map(tag => `<span class="demand-tag">${tag}</span>`).join('')}
                        </div>
                    </div>
                ` : ''}
                
                ${demand.workflow ? `
                    <div class="workflow-section">
                        <h4>流程进度</h4>
                        <div id="modal-workflow-preview"></div>
                    </div>
                ` : ''}
            </div>
        `;
        
        // 显示流程预览
        if (demand.workflow) {
            const workflowContainer = document.getElementById('modal-workflow-preview');
            if (workflowContainer) {
                const workflowPreview = new WorkflowPreview(workflowContainer);
                workflowPreview.setWorkflow(demand.workflow);
            }
        }
        
        modal.classList.add('active');
    }
    
    /**
     * 关闭模态框
     */
    closeModal() {
        document.querySelectorAll('.modal').forEach(modal => {
            modal.classList.remove('active');
        });
    }
    
    /**
     * 获取状态文本
     */
    getStatusText(status) {
        const statusMap = {
            'pending': '待处理',
            'in_progress': '进行中',
            'completed': '已完成',
            'rejected': '已拒绝'
        };
        
        return statusMap[status] || status;
    }
    
    /**
     * 获取表单数据
     */
    getFormData(formId) {
        const form = document.getElementById(formId);
        const formData = new FormData(form);
        const data = {};
        
        for (let [key, value] of formData.entries()) {
            data[key] = value;
        }
        
        // 手动获取一些字段
        const inputs = form.querySelectorAll('input, select, textarea');
        inputs.forEach(input => {
            if (input.name) {
                data[input.name] = input.value;
            }
        });
        
        return data;
    }
    
    /**
     * 重置表单
     */
    resetForm(formId) {
        const form = document.getElementById(formId);
        if (form) {
            form.reset();
        }
    }
    
    /**
     * HTML转义
     */
    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
    
    /**
     * 显示加载状态
     */
    showLoading(show) {
        const loading = document.getElementById('loading');
        if (loading) {
            loading.classList.toggle('active', show);
        }
    }
    
    /**
     * 显示消息
     */
    showMessage(message, type = 'info') {
        const container = document.getElementById('message-container');
        if (!container) return;
        
        const messageEl = document.createElement('div');
        messageEl.className = `message ${type}`;
        messageEl.textContent = message;
        
        container.appendChild(messageEl);
        
        // 3秒后自动移除
        setTimeout(() => {
            if (messageEl.parentNode) {
                messageEl.parentNode.removeChild(messageEl);
            }
        }, 3000);
    }
}

// 创建全局应用实例
window.app = new TaskTrackApp();

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    window.app.init();
});